/*
 * @Author: ljk
 * @Date: 2023-06-01 13:51:39
 * @LastEditors: ljk
 * @LastEditTime: 2023-06-01 14:53:53
 * @Description: 线程封装
 */
#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <pthread.h>
#include <functional>

class Thread
{
public:
    typedef enum
    {
        NEW = 0,
        RUNNING,
        EXITED
    } ThreadStatus;
    typedef void *(*func_t)(void *);

public:
    Thread(int num, func_t func, void *args) : _tid(0), _status(NEW), _func(func), _args(args)
    {
        char name[128];
        snprintf(name, sizeof(name), "thread-%d", num);
        _name = name;
    }
    int status() { return _status; }
    std::string threadName()
    {
        return _name;
    }
    pthread_t threadId()
    {
        if (_status == RUNNING)
        {
            return _tid;
        }
        else
        {
            return 0;
        }
    }
    // 为什么此处会报错?
    // 是类的成成员函数，有一个默认参数this, 所以是参数不匹配
    // static可以解决，但是会带来新的问题, 无法直接访问类属性和其它成员函数
    //  void* runHelper(void* args)
    //  {

    // }
    static void *runHelper(void *args)
    {
        Thread *ts = (Thread *)args;
        // 非静态成员
        // ts->_func(_args);
        (*ts)();

        return nullptr;
    }
    // 运算符重载
    void operator()()
    {
        if (_func != nullptr)
        {
            _func(_args);
        }
    }
    void run()
    {
        int n = pthread_create(&_tid, nullptr, runHelper, this);
        if (n != 0)
        {
            exit(1);
        }
        _status = RUNNING;
    }
    void join()
    {
        int n = pthread_join(_tid, nullptr);
        if (n != 0)
        {
            std::cerr << "main thread join thread " << _name << " error" << std::endl;
            return;
        }
        _status = EXITED;
    }
    ~Thread()
    {
    }

private:
    pthread_t _tid;
    std::string _name;
    func_t _func; // 线程未来要执行的回调方法
    void *_args;
    ThreadStatus _status;
};